package cn.linjianhui.thread.Lock;

import javafx.scene.layout.Priority;

import java.util.concurrent.locks.ReentrantLock;

public class TryLock implements Runnable {

    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();
    public int lock;

    public TryLock(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        if(lock == 1) {
            while(true) {
                if (lock1.tryLock()) {
                    // 当程序执行try{}遇到return时，程序会先执行return语句，但并不会立即返回
                    // 当finally块执行完成后就直接返回
                    try {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        }

                        if (lock2.tryLock()) {
                            try {
                                System.out.println(Thread.currentThread().getId() + ":My Job done");
                                return;
                            } finally {
                                if (lock2.isHeldByCurrentThread()) {
                                    System.out.println("lock = 1, lock2解锁");
                                    lock2.unlock();
                                }
                            }
                        }
                    }finally {
                        lock1.unlock();
                    }
                }
            }
        }else {
            while(true) {
                if(lock2.tryLock()) {
                    try {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        }

                        if (lock1.tryLock()) {
                            try {
                                System.out.println(Thread.currentThread().getId() + ":My Job done");
                                return;
                            } finally {
                                if (lock1.isHeldByCurrentThread()) {
                                    System.out.println("lock = 2, lock1解锁");
                                    lock1.unlock();
                                }
                            }
                        }
                    }finally {
                        lock2.unlock();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new TryLock(1));
        Thread t2 = new Thread(new TryLock(2));
        t1.start(); t2.start();
    }
}
